<template>
  <el-dialog
    title="产品"
    :visible.sync="dialogShow"
    width="80%"
    :before-close="closeDialog"
    :close-on-click-modal="false"
  >
    <div>
      <search-form
        ref="searchForm"
        :search-config="searchConfig"
        :label-width="100"
        @clear="clearSearch"
        @search="handleSearch"
      />
    </div>
    <el-tabs v-model="activeName" @tab-click="changeTab">
      <el-tab-pane label="全部" name="all">
        <div class="table-list-box">
          <el-table
            ref="multipleTable"
            v-loading="tableLoading"
            :data="tableData"
            border
            max-height="220"
            header-row-class-name="table-list-header"
            :row-class-name="tableRowClassName"
            tooltip-effect="dark"
            style="width: 100%"
            @row-click="selectRow"
            @select="selectTable"
            @select-all="selectionAll"
            @selection-change="selectChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="productCode" label="产品编码" width="120" show-overflow-tooltip />
            <el-table-column prop="productName" label="产品描述" show-overflow-tooltip />
            <el-table-column prop="productModel" label="型号" width="120" show-overflow-tooltip />
            <el-table-column prop="productCategoryName" label="品类" width="140" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.parentName || scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="saleSeriesName" label="产品系列" width="120" show-overflow-tooltip />
            <!-- <el-table-column prop="proPosition" label="产品定位" width="120" /> -->
          </el-table>
        </div>
        <div class="pagination-box">
          <div class="pagination-container">
            <el-pagination
              :current-page.sync="currentPage"
              :page-sizes="pageSizelist"
              :page-size="pageSize"
              layout="sizes, prev, pager, next, slot"
              :total="allTotal === 0 ? total : allTotal"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            >
              <span class="el-pagination__jump">前往
                <el-input-number
                  v-model="jumpPage"
                  :controls="false"
                  :min="1"
                  @blur="showEnter"
                  @keyup.enter.native="showEnter"
                />页</span>
            </el-pagination>
            <div v-show="total <= pageSize" class="pagination-info">当前显示
              <span>{{ handlePageRange(pageSize, currentPage) }}</span>，共
              <span class="total"> {{ tableData.length }} </span> 条记录
            </div>
            <div v-show="total > pageSize" class="pagination-info">当前显示
              <span>{{ handlePageRange(pageSize, currentPage) }}</span>，共
              <span :class="[allTotal === 0 && total !== 0 ? 'total next-page': 'total']" @click="newEnter"> {{ allTotal === 0 && total !== 0 ? total-1 +'+': allTotal }}  </span> 条记录
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="`已选择(${selectedData.length})`" name="selected">
        <div class="table-list-box">
          <el-table
            ref="chosenTable"
            :data="showSelectedData"
            border
            max-height="220"
            header-row-class-name="table-list-header"
            highlight-current-row
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column prop="productCode" label="产品编码" width="120" show-overflow-tooltip />
            <el-table-column prop="productName" label="产品描述" show-overflow-tooltip />
            <el-table-column prop="productModel" label="型号" width="120" show-overflow-tooltip />
            <el-table-column prop="productCategoryName" label="品类" width="140" show-overflow-tooltip />
            <el-table-column prop="saleSeriesName" label="产品系列" width="120" show-overflow-tooltip />
            <el-table-column label="操作" width="60">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  style="color:#3dc094; cursor: pointer;"
                  @click="deleteChose(scope.$index,scope.row)"
                >删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- <div style="margin:10px 0;display:inlnk-black;font-size: 14px;">已选择
      <span style="color:#0f3eea;">{{ selectedData.length }}</span>条数据
    </div> -->

    <div slot="footer">
      <el-button v-if="type !== 'change'" size="mini" @click="handleClose">上一步</el-button>
      <el-button v-if="type === 'change'" size="mini" @click="closeDialog">取 消</el-button>
      <el-button type="primary" size="mini" @click="determineChosen">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getProductList, queryCategoryData, queryBigStyleData } from '@/api/proConfig'

export default {
  name: 'AddProduct',
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    detailData: {
      type: [String, Object],
      default: ''
    },
    otherFilter: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      activeName: 'all',
      showSelectedData: [],
      codeList: [],
      parentCodeList: [],
      type: '',
      tableLoading: false,
      searchConfig: [
        { label: '产品编码', prop: 'productCode', type: 'text', value: '', placeholder: '' },
        { label: '产品描述', prop: 'productName', type: 'text', value: '', placeholder: '', single: true },
        {
          label: '型号',
          prop: 'productModel',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post', // 远程搜索请求方式
            remoteUrl: `/select-service/api/v1/productModel/page`, // 远程搜索API地址
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name', // productSaleSeriesName
              value: 'code' // code
            }, // api返回数据默认字段
            multiple: false
          },
          dialogConfig: {
            title: '型号',
            interfacePath: '/select-service/api/v1/productModel/page',
            setting: [
              { prop: 'code', title: '系列编码' },
              { prop: 'name', title: '系列名称' }
            ]
          }
        },
        {
          label: '品类',
          prop: 'productCategoryCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post', // 远程搜索请求方式
            remoteUrl: `/select-service/api/v1/productCategory/page`, // 远程搜索API地址
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name', // productSaleSeriesName
              value: 'code' // code
            }, // api返回数据默认字段
            multiple: false
          },
          dialogConfig: {
            title: '品类',
            interfacePath: '/select-service/api/v1/productCategory/page',
            setting: [
              { prop: 'code', title: '系列编码' },
              { prop: 'name', title: '系列名称' }
            ]
          }
        },
        {
          label: '产品系列',
          prop: 'saleSeriesCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post', // 远程搜索请求方式
            remoteUrl: `/select-service/api/v1/productSaleSeries/page`, // 远程搜索API地址
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name', // productSaleSeriesName
              value: 'code' // code
            }, // api返回数据默认字段
            multiple: false

          },
          dialogConfig: {
            title: '系列',
            interfacePath: '/select-service/api/v1/productSaleSeries/page',
            setting: [
              { prop: 'code', title: '系列编码' },
              { prop: 'name', title: '系列名称' }
            ]
          }
        }
      ],
      pageSize: 5,
      pageSizelist: [5, 10, 15, 20],
      currentPage: 1,
      total: '',
      jumpPage: '',
      allTotal: 0,
      selectedData: [],
      tableData: [],
      otherFilters: [{ 'id': 'proState', 'property': 'proState', 'operator': '=', 'value': 'E' },
        { 'id': 'customizeType', 'property': 'customizeType', 'operator': '=', 'value': 'NORM' },
        { 'id': 'isSaleProduct', 'property': 'isSaleProduct', 'operator': '=', 'value': '1' }],
      formData: {
        seriesName: '',
        seriesCode: '',
        productName: '',
        productRadio: '1',
        productCode: '' // 62323901101 669325001
      },
      productList: {
        show: false,
        text: '123'
      },
      hasProd: false,
      modelAndCategoryParams: [],
      tmpOtherArr: [],
      detailArr: [],
      categoryArr: []
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.selectedData = []
          this.$nextTick(() => {
            this.$refs.multipleTable.clearSelection()
          })
        }
      }
    }
  },
  async created() {
    this.type = this.detailData.type
    console.log('type', this.type)
    const modelAndCategoryParams = []
    const selectedPro = []
    if (this.detailData.otherFilter) {
      this.detailArr = JSON.parse(JSON.stringify(this.detailData.otherFilter))
      console.log('产品看搭配', this.detailArr)
      let plCodesArr = this.detailArr.map(item => item.categoryCodes)
      // if (!this.type) {
      const matchArr = this.detailArr.filter(item => item.recommendType === 'MATCH')
      const recommendArr = this.detailArr.filter(item => item.recommendType === 'RECOMMEND')
      let matchplArr = []
      let recommendPlArr = []
      if (matchArr.length) {
        matchplArr = matchArr.map(item => item.detailCategoryCode)
      }
      if (recommendArr.length) {
        recommendPlArr = recommendArr.map(item => item.categoryCodes)
      }
      plCodesArr = [...matchplArr, ...recommendPlArr]
      // }
      const plCodes = this.removeEqualData(plCodesArr)
      const plDataArr = await this.getCategoryData(plCodes, 'A')
      const unFinalLevel = plDataArr.filter(item => item.isFinalLevel === '0')
      const finalLevel = plDataArr.filter(item => item.isFinalLevel === '1')
      const unFinalPlArr = unFinalLevel.map(item => item.code)
      const plfinaArr = await this.getCategoryData(unFinalPlArr, 'B')
      this.categoryArr = [...finalLevel, ...plfinaArr]
      this.detailArr.forEach(row => {
        row.childCode = []
        this.categoryArr.forEach(item => {
          if (row.recommendType !== 'MATCH') {
            if (item.parentCode && item.parentCode === row.categoryCodes) {
              row.childCode.push(item.code)
              const obj1 = {
                productModel: row.modelCode,
                productCategoryCode: item.code
              }
              modelAndCategoryParams.push(obj1)
            } else if (!item.parentCode && item.code === row.categoryCodes) {
              row.childCode.push(item.code)
              const obj2 = {
                productModel: row.modelCode,
                productCategoryCode: item.code
              }
              modelAndCategoryParams.push(obj2)
            }
          } else {
            if (item.parentCode && item.parentCode === row.detailCategoryCode) {
              row.childCode.push(item.code)
              const obj1 = {
                productModel: row.modelCode,
                productCategoryCode: item.code
              }
              modelAndCategoryParams.push(obj1)
            } else if (!item.parentCode && item.code === row.detailCategoryCode) {
              row.childCode.push(item.code)
              const obj2 = {
                productModel: row.modelCode,
                productCategoryCode: item.code
              }
              modelAndCategoryParams.push(obj2)
            }
          }
        })
        if (row.productCode) {
          selectedPro.push(row)
        }
      })
      // this.detailData.otherFilter.forEach(item => {
      //   const obj = {
      //     productModel: item.modelCode,
      //     productCategoryCode: item.categoryCodes
      //   }
      //   modelAndCategoryParams.push(obj)
      //   if (item.productCode) {
      //     selectedPro.push(item)
      //   }
      // })
    }
    this.modelAndCategoryParams = [...modelAndCategoryParams]
    let tmpOtherArr = []
    if (selectedPro.length) {
      this.hasProd = true
      const proStrArr = selectedPro.map(item => item.productCode)
      const proStr = '[' + proStrArr.join(',') + ']'
      tmpOtherArr = [{ 'id': 'productCode', 'property': 'productCode', 'operator': 'not in', 'value': proStr }]
    }
    this.tmpOtherArr = [...tmpOtherArr]
    this.modelListAll(1, this.pageSize, false)
  },
  mounted() {},
  methods: {
    removeEqualData(arr) {
      const newArr = []
      for (var i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) === -1) {
          newArr.push(arr[i])
        }
      }
      return newArr
    },
    // 获取品类
    async getCategoryData(arr, flag) {
      const codes = '[' + arr.join(',') + ']'
      let filterRow = []
      if (flag === 'A') {
        filterRow = [{ 'id': 'code', 'property': 'code', 'operator': 'in', 'value': codes }]
      } else if (flag === 'B') {
        filterRow = [{ 'id': 'parentCode', 'property': 'parentCode', 'operator': 'in', 'value': codes }]
      }
      const dataForm = new FormData()
      dataForm.append('pageFlag', false)
      dataForm.append('filtersRaw', JSON.stringify(filterRow))
      // let list = []
      return await queryCategoryData(dataForm).then(res => {
        if (res.success) {
          // if (flag === 'A') {
          //   list = res.data.records
          // } else {
          //   list = res.data.records
          // }
          return res.data.records
        }
      })
    },
    // 获取专区
    async getBigStyleData(arr) {
      const codes = '[' + arr.join(',') + ']'
      const filterRow = [{ 'id': 'seriesCode', 'property': 'seriesCode', 'operator': 'in', 'value': codes }]
      const dataForm = new FormData()
      dataForm.append('pageFlag', false)
      dataForm.append('filtersRaw', JSON.stringify(filterRow))
      return await queryBigStyleData(dataForm).then(res => {
        if (res.success) {
          return res.data.records
        }
      })
    },
    // 清空搜索条件
    clearSearch(data) {
      this.otherFilters = [
        { 'id': 'proState', 'property': 'proState', 'operator': '=', 'value': 'E' },
        { 'id': 'customizeType', 'property': 'customizeType', 'operator': '=', 'value': 'NORM' },
        { 'id': 'isSaleProduct', 'property': 'isSaleProduct', 'operator': '=', 'value': '1' }
      ]
      // this.currentPage = 1
      // this.pageSize = 5
    },
    // 获取搜索条件
    handleSearch(data) {
      const otherArr = [
        { 'id': 'proState', 'property': 'proState', 'operator': '=', 'value': 'E' },
        { 'id': 'customizeType', 'property': 'customizeType', 'operator': '=', 'value': 'NORM' },
        { 'id': 'isSaleProduct', 'property': 'isSaleProduct', 'operator': '=', 'value': '1' }
      ]
      this.otherFilters = [...otherArr, ...data.filtersRaw]
      this.currentPage = 1
      this.pageSize = 5
      if (this.activeName === 'all') {
        const dtos = {
          modelAndCategoryParams: this.modelAndCategoryParams,
          queryParams: {
            page: this.currentPage,
            rows: this.pageSize,
            pageFlag: true,
            onlyCountFlag: false,
            filtersRaw: JSON.stringify([...this.otherFilters, ...this.tmpOtherArr])
          }
        }
        this.onParams(dtos)
      } else {
        if (!this.selectedData.length) return
        if (data.filtersRaw && data.filtersRaw.length) {
          const arr = []
          this.selectedData.forEach(item => {
            const productCodeList = data.filtersRaw.filter(item => item.property === 'productCode')
            const productNameList = data.filtersRaw.filter(item => item.property === 'productName')
            const productModelList = data.filtersRaw.filter(item => item.property === 'productModel')
            const saleSeriesList = data.filtersRaw.filter(item => item.property === 'saleSeriesCode')
            const categoryList = data.filtersRaw.filter(item => item.property === 'productCategoryCode')
            let flag1 = true
            let flag2 = true
            let flag3 = true
            let flag4 = true
            let flag5 = true
            if (productCodeList.length) {
              if (productCodeList[0].operator === 'like') {
                flag1 = (item.productCode.search(productCodeList[0].value) !== -1)
              } else {
                const proCode = JSON.parse(productCodeList[0].value)
                flag1 = proCode.includes(Number(item.productCode))
              }
            }
            if (productNameList.length) {
              flag2 = (item.productName.search(productNameList[0].value) !== -1)
            }
            if (productModelList.length) {
              flag3 = (item.productModel === productModelList[0].value)
            }
            if (saleSeriesList.length) {
              flag4 = (item.saleSeriesCode === saleSeriesList[0].value)
            }
            if (categoryList.length) {
              flag5 = (item.productCategoryCode === categoryList[0].value)
            }
            if (flag1 && flag2 && flag3 && flag4 && flag5) {
              arr.push(item)
            }
          })
          this.showSelectedData = arr
        } else {
          this.showSelectedData = this.selectedData
        }
      }
    },
    modelListAll(currentPage, rows, onlyCountFlag) {
      this.tableLoading = true
      const dtos = {
        modelAndCategoryParams: this.modelAndCategoryParams,
        queryParams: {
          page: currentPage,
          rows: rows,
          pageFlag: true,
          onlyCountFlag: onlyCountFlag,
          filtersRaw: JSON.stringify([...this.otherFilters, ...this.tmpOtherArr])
        }
      }
      getProductList(dtos).then(res => {
        if (res.success && res.data && res.data.records) {
          if (!onlyCountFlag) {
            this.tableData = res.data.records
            this.total = res.data.total
            if (this.total <= this.currentPage * this.pageSize) {
              this.allTotal = this.total
            }
            const selectIds = this.selectedData.map(e => {
              return e.productCode
            })
            // 表格数据对比是否存在已选择数据并对其勾选
            this.tableData.forEach(item => {
              if (selectIds.includes(item.productCode)) {
                this.$nextTick(() => {
                  this.$refs.multipleTable.toggleRowSelection(item)
                })
              }
            })
          } else {
            this.allTotal = res.data.total
            this.total = res.data.total
            this.currentPage = res.data.page
          }
        }
        this.showSelectedData = this.selectedData
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 去重
    unique(arr, flag) {
      const res = new Map()
      return arr.filter((arr) => !res.has(arr[flag]) && res.set(arr[flag], 1))
    },
    // 确定
    async determineChosen() {
      const prodPicDetail = []
      if (!this.selectedData.length) {
        this.detailData.otherFilter.forEach(item => {
          const obj = {
            outpicCategoryNumberId: item.outpicCategoryNumberId,
            areaCode: item.areaCode,
            areaName: item.areaName,
            spaceTotalArea: item.spaceTotalArea,
            spaceCode: item.spaceCode,
            spaceName: item.spaceName,
            styleCode: item.styleCode,
            styleName: item.styleName,
            categoryCodes: item.categoryCodes,
            categoryNames: item.categoryNames,
            modelCode: item.modelCode,
            modelName: item.modelName,
            recommendProgram: item.recommendProgram,
            proPosition: item.proPosition,
            seriesCode: item.seriesCode,
            detailCategoryCode: item.detailCategoryCode,
            detailCategoryName: item.detailCategoryName,
            detailSeriesCode: item.detailSeriesCode,
            detailSeriesName: item.detailSeriesName,
            productCode: '',
            productDesc: '',
            productArr: [],
            productState: '',
            pcontrolState: '',
            recommendType: item.recommendType
          }
          prodPicDetail.push(obj)
        })
      } else {
        const equalArr = []
        const tmpSelectList = JSON.parse(JSON.stringify(this.selectedData))
        this.selectedData.forEach((select, sIndex) => {
          tmpSelectList.forEach((t, tindex) => {
            if (sIndex !== tindex && select.productModel === t.productModel && select.productCategoryCode === t.productCategoryCode) {
              equalArr.push(t)
            }
          })
        })
        if (equalArr.length) {
          const arr = this.unique(equalArr, 'productModel')
          arr.forEach(item => {
            item.msg = `型号为${item.productModel}，品类为${item.productCategoryName}的数据存在重复现象，是否重复选择`
          })
          const msgArr = arr.map(a => a.msg)
          let cancelSelect = false
          await this.$confirm(msgArr, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

          }).catch(() => {
            this.$message('取消选择')
            cancelSelect = true
          })
          if (cancelSelect === true) return
        }
        if (this.detailData.otherFilter) {
          console.log('型号数据', this.detailArr)
          this.detailArr.forEach(item => {
            this.selectedData.forEach(select => {
              if (item.modelCode === select.productModel && item.childCode.includes(select.productCategoryCode)) {
                const obj = {
                  outpicCategoryNumberId: item.outpicCategoryNumberId,
                  areaCode: item.areaCode,
                  areaName: item.areaName,
                  spaceTotalArea: item.spaceTotalArea,
                  spaceCode: item.spaceCode,
                  spaceName: item.spaceName,
                  styleCode: item.styleCode,
                  styleName: item.styleName,
                  categoryCodes: item.categoryCodes,
                  categoryNames: item.categoryNames,
                  detailCategoryCode: item.detailCategoryCode,
                  detailCategoryName: item.detailCategoryName,
                  detailSeriesCode: item.detailSeriesCode,
                  detailSeriesName: item.detailSeriesName,
                  modelCode: item.modelCode,
                  modelName: item.modelName,
                  recommendProgram: item.recommendProgram,
                  proPosition: item.proPosition,
                  seriesCode: item.seriesCode,
                  seriesName: item.seriesName,
                  productCode: select.productCode,
                  productDesc: select.productName,
                  productArr: [{ label: select.productName, value: select.productCode }],
                  productState: select.proState,
                  pcontrolState: select.canBePurchase,
                  recommendType: item.recommendType
                }
                prodPicDetail.push(obj)
              }
            })
          })
          console.log('prodPicDetail', prodPicDetail)
          const noProArr = this.detailData.otherFilter.filter(row => {
            const index = prodPicDetail.findIndex(item => item.modelCode === row.modelCode)
            return index === -1
          })
          noProArr.forEach(item => {
            const obj = {
              outpicCategoryNumberId: item.outpicCategoryNumberId,
              areaCode: item.areaCode,
              areaName: item.areaName,
              spaceTotalArea: item.spaceTotalArea,
              spaceCode: item.spaceCode,
              spaceName: item.spaceName,
              styleCode: item.styleCode,
              styleName: item.styleName,
              categoryCodes: item.categoryCodes,
              categoryNames: item.categoryNames,
              detailCategoryCode: item.detailCategoryCode,
              detailCategoryName: item.detailCategoryName,
              detailSeriesCode: item.detailSeriesCode,
              detailSeriesName: item.detailSeriesName,
              modelCode: item.modelCode,
              modelName: item.modelName,
              recommendProgram: item.recommendProgram,
              proPosition: item.proPosition,
              seriesCode: item.seriesCode,
              seriesName: item.seriesName,
              productCode: '',
              productDesc: '',
              productArr: [],
              productState: '',
              pcontrolState: '',
              recommendType: item.recommendType
            }
            prodPicDetail.push(obj)
          })
        }
      }
      this.confirmSubmit(prodPicDetail)
    },
    async confirmSubmit(prodPicDetail) {
      const tmpArr = []
      prodPicDetail.forEach(item => {
        const obj = {
          outpicCategoryNumberId: item.outpicCategoryNumberId,
          areaCode: item.areaCode,
          areaName: item.areaName,
          categoryCodes: item.categoryCodes,
          categoryNames: item.categoryNames,
          detailCategoryCode: item.detailCategoryCode,
          detailCategoryName: item.detailCategoryName,
          detailSeriesCode: item.detailSeriesCode,
          detailSeriesName: item.detailSeriesName,
          seriesCode: item.seriesCode,
          seriesName: item.seriesName,
          spaceTotalArea: item.spaceTotalArea,
          spaceCode: item.spaceCode,
          spaceName: item.spaceName,
          styleCode: item.styleCode,
          styleName: item.styleName,
          configDetailDtos: []
        }
        // obj.configDetailDtos = []
        // if (item.productCode) {
        const tmpSelect = {
          modelCode: item.modelCode,
          modelName: item.modelName,
          detailCategoryCode: item.detailCategoryCode,
          recommendProgram: item.recommendProgram,
          proPosition: item.proPosition,
          recommendType: item.recommendType,
          productCode: item.productCode,
          productDesc: item.productDesc,
          productArr: [{ label: item.productDesc, value: item.productCode }],
          productState: item.productState,
          pcontrolState: item.pcontrolState,
          productNumber: 1
        }
        obj.configDetailDtos.push(tmpSelect)
        // }
        tmpArr.push(obj)
      })
      const tmpStyleArr = tmpArr.filter(item => item.detailSeriesCode)
      const styleCodesArr = tmpStyleArr.map(item => item.detailSeriesCode)
      const styleCodes = this.removeEqualData(styleCodesArr)
      const bigStyleArr = await this.getBigStyleData(styleCodes)
      tmpArr.forEach(item => {
        bigStyleArr.forEach(row => {
          if (row.seriesCode === item.detailSeriesCode) {
            item.detailStyleCode = row.bigStyleCode
            item.detailStyleName = row.bigStyleName
          }
        })
      })
      // return
      const finish = {
        type: this.type,
        hasProd: this.hasProd,
        dataList: JSON.parse(JSON.stringify(tmpArr))
      }
      // const finish = JSON.parse(JSON.stringify(tmpArr))
      this.$emit('success', finish)
      this.closeDialog()
      this.dialogShow = false
    },
    // 前往第几页
    showEnter(ev) {
      this.jumpPage = ev.srcElement.value
      this.getTotal(this.jumpPage)
    },
    // 获取总数据条数
    newEnter() {
      this.getTotal(this.currentPage)
    },
    // 当操作在非第一页时，跳回第一页
    jumpToFirstPage() {
      this.currentPage = 1 // 不在第一页搜索时，调回第一页显示
      this.jumpPage = 1
      this.allTotal = 0
      this.total = 0
    },
    // 分页，获取下一页数据
    handleCurrentChange(currentPage) {
      this.jumpPage = currentPage
      this.currentPage = currentPage
      this.$refs.multipleTable.clearSelection()
      this.$refs.chosenTable.clearSelection()
      this.modelListAll(this.currentPage, this.pageSize, false)
    },
    // 分页数据获取---> this.$refs.chosenTable/multipleTable.clearSelection
    handleSizeChange(val) {
      this.pageSize = val
      this.$refs.multipleTable.clearSelection()
      this.$refs.chosenTable.clearSelection()
      this.jumpToFirstPage()
      this.modelListAll(this.currentPage, this.pageSize, false)
    },
    // 计算当前数据范围 如:1-20
    handlePageRange(size, currentPage) {
      const start = size * (currentPage - 1) + 1
      const end = size * currentPage

      const pageRange = `${start}-${end}`
      return pageRange
    },
    // 获取数据总条数
    getTotal(val) {
      if (this.allTotal !== 0) return
      let page = this.currentPage
      if (val) {
        page = val
      }
      this.modelListAll(page, this.pageSize, true)
      this.$nextTick(() => {
        this.modelListAll(page, this.pageSize, false)
      })
    },
    setTBIndex({ row, rowIndex }) {
      // 把每一行的索引放进row
      row.index = rowIndex
    },
    onParams(data) {
      this.tableLoading = true
      getProductList(data).then(res => {
        if (res.success && res.data && res.data.records) {
          this.tableData = res.data.records
          this.total = res.data.total
          if (this.total <= this.currentPage * this.pageSize) {
            this.allTotal = this.total
          }
          const selectIds = this.selectedData.map(e => {
            return e.productCode
          })
          // 表格数据对比是否存在已选择数据并对其勾选
          this.tableData.forEach(item => {
            if (selectIds.includes(item.productCode)) {
              this.$nextTick(() => {
                this.$refs.multipleTable.toggleRowSelection(item)
              })
            }
          })
        }
        this.showSelectedData = this.selectedData
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    handleClose() {
      this.dialogShow = false
      this.$emit('update:visible', false)
      const obj = {
        flag: '',
        lastSelected: this.detailData.lastSelected
      }
      if (this.type === 'recommend') {
        obj.flag = 'recommend'
        this.$emit('goLastPage', obj)
      } else if (this.type === 'match') {
        obj.flag = 'match'
        this.$emit('goLastPage', obj)
      }
    },
    closeDialog() {
      this.dialogShow = false
      this.$emit('update:visible', false)
    },
    selectionAll(val) {
      const selectIds = this.selectedData.map(e => {
        return e.productCode
      })
      val.length &&
        val.forEach(item => {
          if (!selectIds.includes(item.productCode)) {
            this.selectedData = this.selectedData.concat(item)
          }
        })
      if (!val.length) {
        this.tableData.forEach(item => {
          this.selectedData.forEach((s, index) => {
            if (s.productCode === item.productCode) {
              this.selectedData.splice(index, 1)
            }
          })
        })
      }
      this.showSelectedData = this.selectedData
    },
    // 产品数据手动勾选
    selectTable(val, row) {
      if (this.selectedData.length > 0) {
        // 筛选已勾选的code
        const codeList = val.map(e => {
          return e.productCode
        })
        if (codeList.includes(row.productCode)) {
          // 判断是勾选还是取消
          this.selectedData = this.selectedData.concat(row)
        } else {
          this.selectedData.forEach((item, index) => {
            if (item.productCode === row.productCode) {
              this.selectedData.splice(index, 1)
            }
          })
        }
      } else {
        this.selectedData = val
      }
      this.showSelectedData = this.selectedData
      this.$nextTick(() => {
        this.selectedData.forEach(item => {
          this.$refs.chosenTable.toggleRowSelection(item, true)
        })
      })
    },
    // 产品数据手动勾选
    selectRow(row) {
      if (this.selectedData.length > 0) {
        const arr = JSON.parse(JSON.stringify(this.selectedData))
        // 筛选已勾选的code
        const codeList = arr.map(e => {
          return e.productCode
        })
        if (!codeList.includes(row.productCode)) {
          // 判断是勾选还是取消
          this.selectedData = arr.concat(row)
          this.$nextTick(() => {
            this.selectedData.forEach(item => {
              this.$refs.multipleTable.toggleRowSelection(item, true)
            })
          })
        } else {
          this.selectedData.forEach(item => {
            if (item.productCode === row.productCode) {
              this.$refs.multipleTable.toggleRowSelection(item, false)
            }
          })
          this.$nextTick(() => {
            this.selectedData.forEach((item, index) => {
              if (item.productCode === row.productCode) {
                this.selectedData.splice(index, 1)
              }
            })
          })
        }
      } else {
        this.selectedData.push(row)
        this.$nextTick(() => {
          this.selectedData.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        })
      }
      this.showSelectedData = this.selectedData
    },
    deleteChose(index, row) {
      this.selectedData.splice(index, 1)
      this.$nextTick(() => {
        this.tableData.forEach(e => {
          if (e.productCode === row.productCode) {
            this.$refs.multipleTable.toggleRowSelection(e, false)
          }
        })
      })
      this.showSelectedData = this.selectedData
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.selectedData.filter(item => row.productCode === item.productCode)
      return (filterArr.length > 0) ? 'selected-highlight' : ''
    },
    changeTab(tab) {
      this.$refs.searchForm.handleSearch()
    }
  }
}
</script>

<style scoped lang="scss">

</style>
